package com.atguigu.flink.chapter05.sink;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.jdbc.JdbcConnectionOptions;
import org.apache.flink.connector.jdbc.JdbcExecutionOptions;
import org.apache.flink.connector.jdbc.JdbcSink;
import org.apache.flink.connector.jdbc.JdbcStatementBuilder;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2022/1/13 11:02
 */
public class Flink05_Jdbc {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);
        
        DataStream<WaterSensor> stream = env
            .socketTextStream("hadoop162", 9999)
            .map(line -> {
                String[] data = line.split(",");
                return new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2]));
            });
        
        stream
            .keyBy(WaterSensor::getId)
            .sum("vc")
            .addSink(JdbcSink.sink(
                "replace into sensor(id, ts,vc)values(?,?,?)",
                new JdbcStatementBuilder<WaterSensor>() {
                    @Override
                    public void accept(PreparedStatement ps,
                                       WaterSensor ws) throws SQLException {
                        // 只需要做一件事: 给占位符赋值
                        ps.setString(1, ws.getId());
                        ps.setLong(2, ws.getTs());
                        ps.setInt(3, ws.getVc());
                        
                    }
                },
                new JdbcExecutionOptions.Builder()
                    .withBatchIntervalMs(1000)
                    .withBatchSize(2048)
                    .withMaxRetries(3)
                    .build(),
                new JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
                    .withDriverName("com.mysql.jdbc.Driver")
                    .withUrl("jdbc:mysql://hadoop162:3306/test?useSSL=false&characterEncoding=utf-8")
                    .withUsername("root")
                    .withPassword("aaaaaa")
                    .build()
            ));
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
